/**
 * 安装量信息-安装量统计
 * wangmei
 */
import React, { Component } from 'react';
import {Row, Col, Button, Input, DatePicker, Form, Select, message  } from 'antd';
import BreadcrumbCustom from '../../BreadcrumbCustom';
import { getLogInstallGetStatistics, getClassifiesAll } from '../../../Server/SystemManger';
import * as Utils from '../../../common/utils';
import TablePage from '../../TablePage';
import moment from 'moment';
import qs from 'qs';
import * as Const from '../../../common/const';
require('../sysinfo/sysinfo.css');
require('../../systemManager/customer.css');

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';
const Option = Select.Option;
const currentDate = new Date();
let sysCompany = {};
let flag = true;
let state = false;

class Count extends Component{
    constructor(props) {
        super(props);
        let user = JSON.parse(localStorage.getItem('user'));
        sysCompany = user ? user.sysCompany:{};
        flag = Utils.objectIsNull(sysCompany);
        state = flag && sysCompany.id?sysCompany.id==1:false;
        this.state = {
            data: [], //表格数据
            loading: false,
            partNameData: [], //分部名数据
            startIp: flag && sysCompany.startIp, //分部管理起始ip
            endIp: flag && sysCompany.endIp, //分部管理结束ip
            searchText: '',
            filterDropdownVisible: false,
            pagination: {},
        };
    }

    componentWillMount() {
        if(!flag) return;
        this.getPartName();
        const param = {
            queryMonth: [moment(currentDate).format(dateFormat),moment(currentDate).format(dateFormat)],
            page: Const.DEFAULT_PAGE,
            size: Const.DEFAULT_PAGE_SIZE
        }
        this.getDailyChart(param);
    }

    //汇总查询方法
    handleSumSubmit = (e) =>{
        e.preventDefault();
        const { pagination } = this.state;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if(!err){
                values.page = pagination.current?pagination.current- 1:0;
                values.size = this.currentPageSize();
                this.getDailyChart(values);
            }
        });
    }
    //查询汇总方法
    getDailyChart = (values) =>{
        this.setState({ loading: true });
        const { startIp, endIp, pagination } = this.state;
        let startValue = values.startIp?values.startIp : startIp;
        let endValue = values.endIp?values.endIp : endIp;
        const param = {
            startIp: startValue,
            endIp: endValue,
            startDate: moment(values.queryMonth[0]).format(dateFormat),
            endDate: moment(values.queryMonth[1]).format(dateFormat),
            sn: values.sn,
            version: values.version,
            distNum: values.distNum,
            page: values.page,
            size: values.size
        };
        const _param = qs.stringify(param);
        getLogInstallGetStatistics(_param).then(res => {
            if(res && res.code == Const.REQUEST_SUCCESS){
                const data = res.data;
                this.setState({
                    data: data.content,
                    loading: false,
                    pagination: Object.assign(this.state.pagination, { total: data.totalElements>100?100:data.totalElements, current: param.page+1, pageSize:param.size }),
                })
            }else {
                this.setState({
                    loading: false
                })
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    /* 翻页 */
    handleTableChange = (pagination) => {
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        this.setState({
            pagination: pager
        });
        let values = this.props.form.getFieldsValue();
        values.page = pagination.current - 1;
        values.size = pagination.pageSize;
        this.getDailyChart(values);
    }

    //分部名选择事件
    partNameSelect = (value, option) =>{
        this.props.form.setFieldsValue({startIp: '', endIp: ''});
        this.setState({
            startIp: option.props.startIp,
            endIp: option.props.endIp
        })
    }

    //获取分部名数据
    getPartName = () =>{
        getClassifiesAll().then(res => {
            if(res && res.code == Const.REQUEST_SUCCESS){
                const data = res.data
                this.setState({
                    partNameData: data,
                });
            }else{
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    //校验起始ip
    checkStartIP = (rule, value, callback) =>{
        let { startIp, endIp } = this.state;
        if(value==''||value==undefined){
            if(sysCompany.id==1){
                callback();
                return ;
            }else{
                callback('请输入起始IP地址！');
                return ;
            }
        }
        if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(!Utils.checkIPValue(value, startIp, endIp)){
            callback('请输入分部范围内的IP地址！');
            return ;
        }else if(!Utils.checkIPCount(this.props.form.getFieldValue("startIp"),this.props.form.getFieldValue("endIp"))){
            callback('起始IP不能大于结束IP');
            return ;
        }
        if(this.props.form.getFieldValue('endIp') && this.props.form.getFieldError('endIp')){
            this.props.form.validateFields(['endIp'],{ force: true });
        }
        callback();
    }

    //校验结束ip
    checkEndIP = (rule, value, callback) =>{
        let { startIp, endIp } = this.state;
        if(value==''||value==undefined){
            if(sysCompany.id==1){
                callback();
                return ;
            }else{
                callback('请输入结束IP地址！');
                return ;
            }
        }
        if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(!Utils.checkIPValue(value, startIp, endIp)){
            callback('请输入分部范围内的IP地址！');
            return ;
        }else if(!Utils.checkIPCount(this.props.form.getFieldValue("startIp"),this.props.form.getFieldValue("endIp"))){
            callback('结束IP不能小于起始IP');
            return ;
        }
        if(this.props.form.getFieldValue('startIp') && this.props.form.getFieldError('startIp')){
            this.props.form.validateFields(['startIp'],{ force: true });
        }
        callback();
    }

    disabledDate = (current) =>{
        // can not select days before today and today
        return current && current.valueOf() > Date.now();
    }

    validateSn = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('序列号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    validateVersion = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('版本号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    currentPageSize = () => this.state.pagination.pageSize || Const.DEFAULT_PAGE_SIZE;

    render(){
        const { getFieldDecorator } = this.props.form;
        const { partNameData, pagination, loading, data } = this.state;
        const partNameOptions = partNameData.map(d => <Option key={d.id} endIp={d.endIp} startIp={d.startIp} >{d.name}</Option>);

        const columns = [
            {
                title: "时间",
                dataIndex: "dateN",
                align: 'center',
                width: '14%',
                render: (text, record)=>{
                    let time = '';
                    if((record.timeN+"").length<6){
                        time = moment('0'+record.timeN, 'HH:mm:ss').format('HH:mm:ss');
                    }else{
                        time = moment(record.timeN, 'HH:mm:ss').format('HH:mm:ss');
                    }
                    return moment(text+"").format(dateFormat)+' '+ time;
                }
            }, {
                title: "序列号",
                dataIndex: "sn",
                align: 'center',
                width: '16%',
            },
            {
                title: "版本号",
                dataIndex: "version",
                align: 'center',
                width: '14%',
            }, {
                title: "IP",
                dataIndex: "ip",
                align: 'center',
                width: '14%',
            }, {
                title: "硬件ID",
                dataIndex: "hid",
                align: 'center',
                width: '14%',
            }, {
                title: "MAC",
                dataIndex: "mac",
                align: 'center',
                width: '14%',
            }, {
                title: "通道号",
                dataIndex: "distnum",
                align: 'center',
                width: '14%',
            }
        ];

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 24 },
                md: 9,
                lg: 7
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 24 },
                md: 15,
                lg: 17
            },
        };

        return(
            <div>
                <BreadcrumbCustom first={"安装量统计"} />
                { flag && <Form onSubmit={this.handleSumSubmit}>
                    <Row>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="通道号"
                            >
                                {getFieldDecorator('distNum')(
                                    <Input maxLength={255}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="版本号"
                            >
                                {getFieldDecorator('version',{
                                    rules: [{
                                        validator: this.validateVersion
                                    }],
                                })(
                                    <Input maxLength={250}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="序列号"
                            >
                                {getFieldDecorator('sn',{
                                    rules: [{
                                        validator: this.validateSn
                                    }],
                                })(
                                    <Input maxLength={250}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <Col span={12}>
                                <FormItem
                                    {...formItemLayout}
                                    label="IP"
                                >
                                    {getFieldDecorator('startIp',{
                                        rules: [{
                                            validator: this.checkStartIP 
                                        }],
                                        initialValue: sysCompany.startIp
                                    })(
                                        <Input maxLength={255}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{ textAlign: 'center'}}>
                                <FormItem>
                                    <label>-</label>
                                </FormItem>
                            </Col>
                            <Col span={10}>
                                <FormItem
                                    wrapperCol= {{
                                            xs: { span: 24 },
                                            sm: { span: 24 },
                                            md: 18,
                                            lg: 20
                                        }
                                    }
                                >
                                    {getFieldDecorator('endIp',{
                                        rules: [{
                                            validator: this.checkEndIP 
                                        }],
                                        initialValue: sysCompany.endIp
                                    })(
                                        <Input maxLength={255}/>
                                    )}
                                </FormItem>
                            </Col>
                        </Col>
                    </Row>
                    <Row>
                        {state&&<Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="分部名"
                            >
                                {getFieldDecorator('partName')(
                                    <Select
                                        showSearch
                                        style={{ width: '100%' }}
                                        optionFilterProp="children"
                                        onSelect={this.partNameSelect}
                                        filterOption={true}
                                    >
                                        {partNameOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>}
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="时 间"
                            >
                                {getFieldDecorator('queryMonth', {
                                    initialValue: [moment( currentDate, dateFormat), moment( currentDate, dateFormat)]
                                })(
                                    <RangePicker  
                                        disabledDate={this.disabledDate}
                                        ranges={{ 
                                            '今天': [moment(), moment()],
                                            '最近七天': [moment().subtract(7, 'days'), moment() ] ,
                                            '最近一个月': [moment().subtract(1, 'month'), moment()] ,
                                            '最近三个月': [moment().subtract(3, 'months'), moment()] 
                                        }}
                                        style={{ width: '101%'}}
                                        format={dateFormat}
                                        placeholder={['开始日期','结束日期']}
                                        onChange={this.onChange} 
                                        allowClear = {false}
                                        locale={{
                                            "lang": {
                                                today: '今天',
                                                yearFormat: "YYYY年",
                                                monthSelect: "选择月份",
                                                yearSelect: "选择年份",
                                            }
                                        }}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={2} className='count-button-margin'>
                            <FormItem>
                                <Button type="primary" htmlType="submit">查询</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>}
                { flag && <TablePage
                    dataSource={data}
                    loading={loading}
                    columns={columns}
                    onChange={this.handleTableChange}
                    pagination={pagination}
                />}
                {!flag && <div>{Const.STATISTICS_NO_PERMISSION}</div>}
            </div>
        )
    }
}

export default Form.create()(Count)